package com.roc.web.action.merinfo;

/**
 * 前后端商户绑定
 */
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.roc.bean.BindMerOper;
import com.roc.bean.BindMerParams;
import com.roc.bean.MerinfoSearchBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.BindMchtService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;

@Controller
@Namespace("/bindMerinfo")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class BindMerinfoAction extends PaginationBaseAction {
	private static Logger logger = Logger.getLogger(BindMerinfoAction.class);
	
	@Autowired
	private IMerchantServices merinfoService;
	
	@Autowired
	private IPagenitionService pagenitionService; 
	@Autowired
	private IPageService pageService; 
	
	@Autowired
	private BindMchtService bindMchtService;
	
	private BindMerinfoSearchCondtion searchCondition;
	
	private String beforeMchtcd;
	
	private String beforeTermId;
	
	private BindMerParams bindMerParams;
	
	private BindMerOper bindMerOper;
	
	
	@Autowired
	private IPowerInfoService powerInfoService;
	
		// 商户查询初始化
		@Action(value = "jspInit", results = {	
				@Result(name =SUCCESS, location = "/pages/merinfo/bindMerinfoList.jsp"),
				@Result(name = ERROR, location = "/error.jsp") })
		public String merinfoListInit() {
			try {
				Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				if (!Role.O_MANAGER.getCode().equals(logingMerchant.getRoleType())
						&& !Role.OPERATORS_COMM.getCode().equals(
								logingMerchant.getRoleType())
						&& !Role.SYSTEM.getCode().equals(logingMerchant.getRoleType()) && !Role.OPERATORS_LEAD.getCode().equals(logingMerchant.getRoleType())) {
					addActionError("无权限访问!!!");
					return ERROR;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return SUCCESS;

		}

		// 商户查询
		@Action(value = "queryList", results = {
				@Result(name = SUCCESS, location = "/pages/merinfo/bindMerinfoList.jsp"),
				@Result(name = ERROR, location = "/error.jsp") })
		public String queryList() {
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			try {
				if (searchCondition == null) {
					searchCondition = (BindMerinfoSearchCondtion) getSearchConditionFromSession();
					if (searchCondition == null) {
						searchCondition = new BindMerinfoSearchCondtion();
					}
				}
				
				Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	            String orgCode=map.get("orgCode");
	            String superRole= map.get("superRole");
	            String opRealId =map.get("opRealId");
	            searchCondition.setRoleId(superRole);
	            if(Role.O_MANAGER.getCode().equals(superRole)){
					searchCondition.setOpId(opRealId);
						
				}else if(Role.AGENT.getCode().equals(superRole)){
					addActionError("无权限访问!!!");
					return ERROR;
				}
				
				int rows = pageService.countSQL(searchCondition);
				List<MerinfoSearchBean> msList = new ArrayList<MerinfoSearchBean>();
				if (rows > 0) {
					searchRsList = pageService.findAllSQL(searchCondition, 
														calcuStart(getCurrentPage()),
														Constance.PAGE_MAX_SIZE);
					if (searchRsList.size() > 0 && searchRsList != null) {
						Iterator iterator = searchRsList.iterator();
						while (iterator.hasNext()) {
							Object[] obj = (Object[]) iterator.next();
							MerinfoSearchBean msb = new MerinfoSearchBean();
							msb.setMid(Constance.Null2EmptyTrim(obj[0]));
							msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
							msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));
							msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
							msb.setPerName(Constance.Null2EmptyTrim(obj[4]));
							String phone=Constance.Null2EmptyTrim(obj[5]);
							if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=phone && phone.length()>4){
								msb.setPerPhone(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号
							}else{
								msb.setPerPhone(phone);//手机号
							}
							
							msb.setInterContact(Constance.Null2EmptyTrim(obj[6]));
							String cardNo=Constance.Null2EmptyTrim(obj[7]);
							if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=cardNo && cardNo.length()>4){
								msb.setCardNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
							}else{
								msb.setCardNo(cardNo);//证件号
							}
							
							msb.setFlagCode(Constance.Null2EmptyTrim(obj[8]));
							msb.setAddr(Constance.Null2EmptyTrim(obj[9]));
							msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[10])));//状态
							msb.setBus_lic(Constance.Null2EmptyTrim(obj[11]));//审核人员名称
							msb.setCompanyName(Constance.Null2EmptyTrim(obj[12]));//所属分公司
							msb.setOneAgentName(Constance.Null2EmptyTrim(obj[13]));//所属代理商
							msb.setAgentId(Constance.Null2EmptyTrim(obj[14]));//直属代理商
							msb.setRsvl(Constance.Null2EmptyTrim(obj[15]));//结算银行账户名称
							String account=Constance.Null2EmptyTrim(obj[16]);
							/*if(account!=null && account.length()>4){
								msb.setRsvl3(account.substring(0, 4)+"****"+account.substring(account.length()-4));//结算银行账户
							}else{*/
								msb.setRsvl3(account);//结算银行账户
							//}
							
							msb.setAmount1(Constance.Null2EmptyTrim(obj[17]));//结算银行名称
							msb.setAmount2(Constance.Null2EmptyTrim(obj[18]));//联行号
							msb.setGroupCd(Constance.Null2EmptyTrim(obj[21])); //商户类型
							/*String[] cycleList=merinfoService.queryMchtBizDealArray(msb.getMid(),true,true);//根据商户查询结算周期
							msb.setMerCycle(cycleList);*/
							String[] productCodeFlag=merinfoService.queryMchtBizDealArray(msb.getMid(), true, false);
							String[] cycleList={"",""};
							if(Constant.STR_NUMBER_ONE.equals(msb.getGroupCd()) && (Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1) ||
									Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0))){	//结算方式处理
								cycleList[0]=Constance.Null2EmptyTrim(obj[25]);
								if(null!=Constance.Null2EmptyTrim(obj[26]) && !Constance.Null2EmptyTrim(obj[26]).equals("")){
									String j="";
									if(null!=cycleList[0] && !cycleList[0].equals("")){
										j="+";
									}
									cycleList[1]=j+Constance.Null2EmptyTrim(obj[26]);
								}
							}else{
								cycleList[0]=Constance.Null2EmptyTrim(obj[19]);
								if(null!=Constance.Null2EmptyTrim(obj[20]) && !Constance.Null2EmptyTrim(obj[20]).equals("")){
									String j="";
									if(null!=cycleList[0] && !cycleList[0].equals("")){
										j="+";
									}
									cycleList[1]=j+Constance.Null2EmptyTrim(obj[20]);
								}
							}
							msb.setMerCycle(cycleList);
							msb.setNationCd(Constance.Null2EmptyTrim(obj[22]).trim());
							msb.setIsGroup(Constance.Null2EmptyTrim(obj[23]));
							msb.setApplDate(Constance.Null2EmptyTrim(obj[24]));
							
					        msb.setTermProperty(Constance.Null2EmptyTrim(obj[27]));
							msb.setCertifDate(Constance.Null2EmptyTrim(obj[28]));
							msb.setBusiLiceDate(Constance.Null2EmptyTrim(obj[29]));
							msb.setDevelopPerson(Constance.Null2EmptyTrim(obj[30]));
							msb.setTermId(Constance.Null2EmptyTrim(obj[31]));
							msb.setSn(Constance.Null2EmptyTrim(obj[32]));
							
							msList.add(msb);
						}
					}

				}
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute("COUNT", rows);//当前条件统计总数
				getRequest().setAttribute(SEARCH_RS_LIST, msList);
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
			 
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				addActionError(e.getMessage());
				return ERROR;
			}
				return SUCCESS;
		}
		
		/**
		 * 查询可供绑定后端商户号页面初始化
		 * @return
		 */
		@Action(value = "queryBindListInit", results = {
				@Result(name = SUCCESS, location = "/pages/merinfo/bindList.jsp"),
				@Result(name = ERROR, location = "/error.jsp") })
		public String queryBindListInit(){
			if(beforeMchtcd == null || "".equals(Constance.Null2EmptyTrim(beforeMchtcd))){
				addActionError("前端商户号为空");
				return ERROR;
			}
			
			if(beforeTermId == null || "".equals(Constance.Null2EmptyTrim(beforeTermId))){
				addActionError("前端终端号为空");
				return ERROR;
			}
			
			getRequest().setAttribute("beforeMchtcd", beforeMchtcd);
			getRequest().setAttribute("beforeTermId", beforeTermId);
			
			return SUCCESS;
			
		}
		
		/**
		 * 查询可供绑定后端商户号
		 * @return
		 */
		@Action(value = "queryBindList", results = {
				@Result(name = SUCCESS, location = "/pages/merinfo/bindList.jsp"),
				@Result(name = ERROR, location = "/error.jsp") })
		public String queryBindList(){
			try {
				
				if(bindMerParams == null){
					bindMerParams = (BindMerParams) getRequest().getSession().getAttribute("bindMerParams");
				}
				
				Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				
				int rows = bindMchtService.queryBindListCount(bindMerParams);
				List<MerinfoSearchBean> msList = new ArrayList<MerinfoSearchBean>();
				if (rows > 0) {
					searchRsList = bindMchtService.queryBindList(bindMerParams, 
														calcuStart(getCurrentPage()),
														Constance.PAGE_MAX_SIZE);
					if (searchRsList.size() > 0 && searchRsList != null) {
						Iterator iterator = searchRsList.iterator();
						while (iterator.hasNext()) {
							Object[] obj = (Object[]) iterator.next();
							MerinfoSearchBean msb = new MerinfoSearchBean();
							msb.setMid(Constance.Null2EmptyTrim(obj[0]));
							msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
							msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));
							msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
							msb.setPerName(Constance.Null2EmptyTrim(obj[4]));
							String phone=Constance.Null2EmptyTrim(obj[5]);
							if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=phone && phone.length()>4){
								msb.setPerPhone(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号
							}else{
								msb.setPerPhone(phone);//手机号
							}
							
							msb.setInterContact(Constance.Null2EmptyTrim(obj[6]));
							String cardNo=Constance.Null2EmptyTrim(obj[7]);
							if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=cardNo && cardNo.length()>4){
								msb.setCardNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
							}else{
								msb.setCardNo(cardNo);//证件号
							}
							
							msb.setFlagCode(Constance.Null2EmptyTrim(obj[8]));
							msb.setAddr(Constance.Null2EmptyTrim(obj[9]));
							msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[10])));//状态
							msb.setBus_lic(Constance.Null2EmptyTrim(obj[11]));//审核人员名称
//							msb.setCompanyName(Constance.Null2EmptyTrim(obj[12]));//所属分公司
//							msb.setOneAgentName(Constance.Null2EmptyTrim(obj[13]));//所属代理商
//							msb.setAgentId(Constance.Null2EmptyTrim(obj[14]));//直属代理商
							msb.setRsvl(Constance.Null2EmptyTrim(obj[15]));//结算银行账户名称
							String account=Constance.Null2EmptyTrim(obj[16]);
							/*if(account!=null && account.length()>4){
								msb.setRsvl3(account.substring(0, 4)+"****"+account.substring(account.length()-4));//结算银行账户
							}else{*/
								msb.setRsvl3(account);//结算银行账户
							//}
							
							msb.setAmount1(Constance.Null2EmptyTrim(obj[17]));//结算银行名称
							msb.setAmount2(Constance.Null2EmptyTrim(obj[18]));//联行号
							msb.setGroupCd(Constance.Null2EmptyTrim(obj[21])); //商户类型
							msb.setNationCd(Constance.Null2EmptyTrim(obj[22]).trim());
							msb.setIsGroup(Constance.Null2EmptyTrim(obj[23]));
							msb.setApplDate(Constance.Null2EmptyTrim(obj[24]));
							msb.setTermId(Constance.Null2EmptyTrim(obj[25]));
							msb.setSn(Constance.Null2EmptyTrim(obj[26]));
							
							msList.add(msb);
						}
					}

				}
				
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute("COUNT", rows);//当前条件统计总数
				getRequest().setAttribute(SEARCH_RS_LIST, msList);
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				getRequest().getSession().setAttribute("bindMerParams", bindMerParams);
				getRequest().setAttribute("beforeMchtcd", beforeMchtcd);
				getRequest().setAttribute("beforeTermId", beforeTermId);
				
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				addActionError(e.getMessage());
				return ERROR;
			}
			
			return SUCCESS;
		}
		
		/**
		 * 绑定后端商户号
		 */
		@Action(value = "bindMerchant",results = {@Result(name = "error", location = "/error.jsp")})
		public String bindMerchant(){

			Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			Map<String,Object> resMap = new HashMap<String, Object>();
			HttpServletResponse response = ServletActionContext.getResponse();
		    response.setCharacterEncoding("UTF-8");
			JSONObject jsonObject = new JSONObject();
			PrintWriter out = null;
			
			try {
				out = response.getWriter();
				resMap = bindMchtService.bindMerchant(logingMerchant,bindMerOper);
				jsonObject.put("resMap", resMap);
				out.print(jsonObject.toString());
				
			} catch (Exception e) {
				addActionMessage("绑定后端商户号异常");
				logger.error("绑定后端商户号失败：",e);
			}
			
			if(out != null){
				out.flush();
				out.close();
			}
			
			return null;
		
		}
		
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	 
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BindMerinfoSearchCondtion) getSession().getAttribute(SEARCH_SESSION_BIND_MERINFO);
	}

	 
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass() throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	 
	@Override
	protected void setSearchConditionToSubClass(BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	 
	@Override
	protected void setSearchToConditionSession(BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BIND_MERINFO, searchCondition);
	}

	public BindMerinfoSearchCondtion getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(BindMerinfoSearchCondtion searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getBeforeMchtcd() {
		return beforeMchtcd;
	}

	public void setBeforeMchtcd(String beforeMchtcd) {
		this.beforeMchtcd = beforeMchtcd;
	}

	public BindMerParams getBindMerParams() {
		return bindMerParams;
	}

	public void setBindMerParams(BindMerParams bindMerParams) {
		this.bindMerParams = bindMerParams;
	}

	public String getBeforeTermId() {
		return beforeTermId;
	}

	public void setBeforeTermId(String beforeTermId) {
		this.beforeTermId = beforeTermId;
	}

	public BindMerOper getBindMerOper() {
		return bindMerOper;
	}

	public void setBindMerOper(BindMerOper bindMerOper) {
		this.bindMerOper = bindMerOper;
	}

	
}
